<template>
    <view class="index-content-box timer" :class="{'timer--running':isRunning}">
        <view class="timer-main">
            <view class="timer-time-wrap">
                <view class="timer-progress-mask"></view>
                <view class="timer-progress timer-left">
                    <view class="timer-circle timer-circle-left"
                          :style="{'transform':'rotate('+leftDeg+'deg)',}"></view>
                </view>
                <view class="timer-progress timer-right">
                    <view class="timer-circle timer-circle-right"
                          :style="{'transform':'rotate('+rightDeg+'deg)',}"></view>
                </view>
                <text v-show="!completed" class="timer-time">{{ remainTimeText }}</text>
                <text v-show="isRunning" :animation="nameAnimation" class="timer-taskName">{{ taskName }}{{ completed ? '已完成!' : '中' }}</text>
                <image v-show="completed" class="timer-done" src="../../static/images/complete.png"></image>
            </view>
            <input v-model="logName" type="text" placeholder-class="timer-inputPlaceholder" class="timer-inputName" placeholder="自定义任务名">
        </view>
        <view class="timer-footer">
            <view class="all-timer-ctrl timer-ctrl" v-if="!(isRunning && timerType === 'rest')" @click="startTimer('work')">
                {{ isRunning ? '退出' : workName }}
            </view>
            <view class="all-timer-ctrl timer-ctrl-2" v-if="!(isRunning && timerType === 'work')" @click="startTimer('rest')">
                {{ isRunning ? '退出' : '休息' }}
            </view>
        </view>
    </view>
</template>

<script>
import util from 'util/index';

const defaultLogName = {
    work: '工作',
    rest: '休息'
};
const actionName = {
    stop: '结束',
    start: '开始'
};
const initDeg = {
    left: 45,
    right: -45,
};

export default {
    data() {
        return {
            remainTimeText: '',
            timerType: 'work',
            log: {},
            completed: false,
            isRunning: false,
            leftDeg: 45,
            rightDeg: -45,
            taskName: "",
            vibison: "",
            workTime: "",
            restTime: "",
            timer: null,//定时器
            nameAnimation:null,//动画
            logName:""
        }
    },
    computed:{
        workName(){
            return this.logName  || '工作';
        }
    },
    onLoad() {

    },
    onShow() {
        if (this.isRunning) return false;
        this.workTime = util.formatTime(uni.getStorageSync('workTime'), 'HH');
        this.restTime = util.formatTime(uni.getStorageSync('restTime'), 'HH');
        this.remainTimeText = this.workTime + ':00'
    },
    onShareAppMessage(from){
        if (from === 'button') {
            return {
                title: '管理时间，保持专注！让自律成为习惯！',
                path: '/pages/index/index',
                imageUrl: '/image/share.jpg' //不设置则默认为当前页面的截图
            }
        }
    },
    methods: {
        startTimer(timerType) {
            this.timerType = timerType;
            const startTime = Date.now();
            const startTimeShow = this.getTime();
            const showTime = this[this.timerType + 'Time'];
            const keepTime = showTime * 60 * 1000;
            this.vibrateShort();
            if (!this.isRunning) {
                this.timer = setInterval(() => {
                    this.updateTime();
                    this.startNameAnimation();
                }, 1000)
            } else {
                this.stopTimer();
            }
            this.isRunning = !this.isRunning;
            this.completed = false;
            this.remainTimeText = showTime + ':00';
            this.taskName = this.logName || defaultLogName[this.timerType];

            this.log = {
                name:this.taskName,
                startTime:Date.now(),
                startTimeShow,
                keepTime,
                endTime:keepTime + startTime,
                action:actionName[this.isRunning ? 'stop' : 'start'],
                type:this.timerType
            }
            this.saveLog(this.log);
        },
        updateTime() {
            const log = this.log;
            const now = Date.now();
            const remainingTime = Math.round((log.endTime - now) / 1000);
            const H = util.formatTime(Math.floor(remainingTime / (60 * 60)) % 24, 'HH');
            const M = util.formatTime(Math.floor(remainingTime / (60)) % 60, 'MM');
            const S = util.formatTime(Math.floor(remainingTime) % 60, 'SS');

            if (remainingTime > 0) {
                this.remainTimeText = (H === '00' ? '' : (H + ':')) + M + ':' + S;
            } else if (remainingTime === 0) {
                this.completed = true;
                this.stopTimer();
                return false;
            }

            const halfTime = log.keepTime / 2;
            if ((remainingTime * 1000) > halfTime) {
                this.leftDeg = initDeg.left - (180 * (now - log.startTime) / halfTime);
            } else {
                this.leftDeg = -135;
                this.rightDeg = initDeg.right - (180 * (now - (log.startTime + halfTime)) / halfTime);
            }
        },
        stopTimer () {
            // reset circle progress
            this.leftDeg = 45;
            this.rightDeg = -45;
            this.vibrateLong()
            this.timer && clearInterval(this.timer)
            //  震动 ；clear timer
        },
        saveLog(log){
            const logs = uni.getStorageSync('logs') || [];
            logs.unshift(log);
            uni.setStorageSync('logs',logs);
        },
        startNameAnimation(){
            const animation = uni.createAnimation({
                duration: 450
            });
            animation.opacity(0.2).step();
            animation.opacity(1).step();
            this.nameAnimation = animation.export();
        },
        vibrateShort() {
            const vibison = uni.getStorageSync('vibison');
            this.vibison = vibison;
            if (vibison) {
                uni.vibrateShort();
            }
        },
        vibrateLong(){
            const vibison = uni.getStorageSync('vibison');
            this.vibison = vibison;
            if (vibison) {
                uni.vibrateLong();
            }
        },
        getTime() {
            const date = new Date();
            const year = this.appendZero(date.getFullYear());
            const month = this.appendZero(date.getMonth() + 1)
            const day = this.appendZero(date.getDate());
            const hours = this.appendZero(date.getHours());
            const minutes = this.appendZero(date.getMinutes());
            const seconds = this.appendZero(date.getSeconds());
            return year + "年 " + month + "月" + day + '日 ' + "\xa0\xa0\xa0" + hours + ":" + minutes + ":" + seconds
        },
        //过滤补0
        appendZero(obj) {
            if (obj < 10) {
                return "0" + obj;
            } else {
                return obj;
            }
        }
    }
}
</script>

<style scoped>
@import "index.css";
</style>
